package com.xhtt.modules.cfg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.Query;
import com.xhtt.modules.cfg.dao.CfgComprodMapper;
import com.xhtt.modules.cfg.entity.*;
import com.xhtt.modules.cfg.service.*;
import com.xhtt.modules.inspection.service.IInsLabelService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 常用产品 服务实现类
 * </p>
 *
 * @author feipc
 * @since 2019-02-19
 */
@Service
public class CfgComprodServiceImpl extends ServiceImpl<CfgComprodMapper, CfgComprod> implements CfgComprodService {

    @Autowired
    private IInsLabelService insLabelService;
    @Autowired
    private CfgHoseProductService hoseProductService;
    @Autowired
    private CfgTubeProductService tubeProductService;
    @Autowired
    private CfgPumpProductService pumpProductService;
    @Autowired
    private CfgPotProductService potProductService;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<CfgComprod> page = new Query<CfgComprod>(params).getPage();
        page.setRecords(baseMapper.queryPage(page, params));
        return new PageUtils(page);
    }

    @Override
    public CfgComprod getByName(String name) {
        return this.getOne(new LambdaQueryWrapper<CfgComprod>().eq(CfgComprod::getName, name).eq(CfgComprod::getStatus, 1));
    }

    @Override
    public void upload(Map<Long, Map<Integer, String>> map) {

        String typeStr = "爆炸品,压缩气体和液化气体,易燃液体,易燃固体,自然物品和遇湿易燃物品,氧化剂和有机过氧化物,有毒品,放射性物品,腐蚀品,其他";
        List types = Arrays.asList(typeStr.split(","));

        Set<Integer> hasErrorLines = new HashSet<>();
        Set<Integer> nameEmptyIndex = new HashSet<>();
        Set<Integer> typeEmptyIndex = new HashSet<>();
        Set<Integer> typeExistIndex = new HashSet<>();

        map.forEach((k, v) -> {
            if (k > 2L) {
                boolean hasError = false;
                try {
                    CfgComprod cfgComprod = new CfgComprod();
                    // 产品名称
                    String name = v.get(0);
                    if (StringUtils.isEmpty(name)) {
                        nameEmptyIndex.add(k.intValue());
                        hasError = true;
                    } else {
                        cfgComprod.setName(name);
                    }

                    // 产品类型
                    String type = v.get(1);
                    if (StringUtils.isEmpty(type)) {
                        typeEmptyIndex.add(k.intValue());
                        hasError = true;
                    } else {
                        if (types.indexOf(type) == -1) {
                            typeExistIndex.add(k.intValue());
                            hasError = true;
                        } else {
                            cfgComprod.setType(type);
                        }
                    }

                    // 备注
                    String memo = v.get(2);
                    if (StringUtils.isNotEmpty(memo)) {
                        cfgComprod.setMemo(memo);
                    }
                    if (!hasError) {
                        this.save(cfgComprod);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    hasErrorLines.add(k.intValue());
                }
            }
        });

        StringBuilder stringBuilder = new StringBuilder();
        if (CollectionUtils.isNotEmpty(hasErrorLines)) {
            stringBuilder.append(insLabelService.formatUploadEx("第", hasErrorLines, "行有错误"));
        }
        if (CollectionUtils.isNotEmpty(nameEmptyIndex)) {
            stringBuilder.append(insLabelService.formatUploadEx("第", nameEmptyIndex, "行产品为空"));
        }
        if (CollectionUtils.isNotEmpty(typeEmptyIndex)) {
            stringBuilder.append(insLabelService.formatUploadEx("第", typeEmptyIndex, "行产品类别为空"));
        }
        if (CollectionUtils.isNotEmpty(typeExistIndex)) {
            stringBuilder.append(insLabelService.formatUploadEx("第", typeExistIndex, "行产品类别不正确"));
        }
        if (StringUtils.isNotEmpty(stringBuilder.toString())) {
            throw new RRException(stringBuilder.toString());
        }

    }

    @Override
    public void updateComprod(CfgComprod cfgComprod) {
        Integer id = cfgComprod.getId();
        String dbName = this.getOne(new LambdaQueryWrapper<CfgComprod>().eq(CfgComprod::getId, id).select(CfgComprod::getId, CfgComprod::getName)).getName();
        String newName = cfgComprod.getName();
        int count = this.count(new LambdaQueryWrapper<CfgComprod>().eq(CfgComprod::getName, newName).ne(CfgComprod::getId, id));
        if (count > 0) {
            throw new RRException("产品名称已存在");
        }
        this.updateById(cfgComprod);
        if (!newName.equals(dbName)) {
            taskExecutor.submit(() -> {
                UpdateWrapper uw = new UpdateWrapper();
                uw.set("name", newName);
                uw.eq("product_id", id);
                hoseProductService.update(new CfgHoseProduct(), uw);
                tubeProductService.update(new CfgTubeProduct(), uw);
                pumpProductService.update(new CfgPumpProduct(), uw);
                potProductService.update(new CfgPotProduct(), uw);
            });
        }
    }
}
